/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import { HelmetProvider } from 'react-helmet-async';
import { match as IMath } from 'react-router';
import React, { useEffect } from 'react';
import { Link, useIntl, connect, Dispatch } from 'umi';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import GlobalFooter from '@/components/GlobalFooter';
import globalStore from '@/store/global';
import { flatTree, isUrl } from '@/utils/utils';
import { UserModule } from '@/services/sys';
import logo from '../assets/img/logo.png';

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  sideBar: MenuDataItem[];
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};

const replaceParams = (path: string, params: object) =>
  path.replace(/:\w+/gi, (placeHolder: string) => params[placeHolder.replace(':', '')] || '');

/**
 * use Authorized check all menu item
 */
const menuDataRender = (routes: any, menuList: UserModule[], match: IMath): MenuDataItem[] =>
  menuList.map((item) => {
    const { url, name, icon, uri } = item;
    const replacePath = isUrl(url) ? url : replaceParams(url, match.params);
    const menu = routes.find((route: any) => route.path === url) || {};

    const localItem = {
      ...menu,
      ...item,
      name,
      path: replacePath,
      icon: menu.icon || icon,
      locale: menu.locale || `menu.${uri}`,
      children: item.children ? menuDataRender(routes, item.children, match) : [],
    };
    return localItem as MenuDataItem;
  });

const footerRender = (siteConfig: any) => {
  return siteConfig && <GlobalFooter copyright={siteConfig.contentFooter} />;
};

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const sideBar = globalStore.useState('sidebar');
  const siteConfig: any = globalStore.useState('siteConfig');
  const { dispatch, settings, match } = props;
  /**
   * constructor
   */

  useEffect(() => {
    if (dispatch) {
      dispatch({ type: 'user/fetchCurrent' });
      globalStore.dispatch('getUserModule');
      globalStore.dispatch('getSite');
    }
  }, []);
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };

  const { formatMessage } = useIntl();
  settings.title = siteConfig.siteName || settings.title;

  return (
    <HelmetProvider>
      <ProLayout
        logo={logo}
        // formatMessage={formatMessage}
        menuHeaderRender={(logoDom, titleDom) => (
          <Link to="/">
            {logoDom}
          </Link>
        )}
        onCollapse={handleMenuCollapse}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
            return defaultDom;
          }

          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        // breadcrumbRender={(routers = []) => [
        //   {
        //     path: '/',
        //     breadcrumbName: formatMessage({
        //       id: 'menu.home',
        //       defaultMessage: 'Home',
        //     }),
        //   },
        //   ...routers,
        // ]}
        itemRender={(routeT, params, routesT, paths) => {
          const first = routesT.indexOf(routeT) === 0;
          return first ? (
            <Link to={paths.join('/')}>{routeT.breadcrumbName}</Link>
          ) : (
            <span>{routeT.breadcrumbName}</span>
          );
        }}
        footerRender={() => footerRender(siteConfig)}
        menuDataRender={(routesT) => {
          const menus = flatTree(routesT, 'children');
          return menuDataRender(menus, sideBar, match);
        }}
        rightContentRender={() => <RightContent />}
        {...props}
        {...settings}
      >
        {/* <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized> */}
      </ProLayout>
    </HelmetProvider>
  );
};

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
